import uvicorn
from fastapi import FastAPI, Body
from fastapi.params import Depends
from pydantic import BaseModel

import config
from api.cbs import api_cbs
from api.ts import api_ts  # 引⼊FastAPI类,⽤于创建⼀个应⽤
from api.zz import api_zz

app = FastAPI()
logger = config.logger()
# include_router()⽅法，⽤于将分发路由添加到app中，prefix参数为路由前缀，tags参数为标签
app.include_router(api_ts, prefix="/ts", tags=["图书"])
app.include_router(api_cbs, prefix="/cbs", tags=["出版社"])
app.include_router(api_zz, prefix="/zz", tags=["作者"])

from fastapi import Request


class Item(BaseModel):
    des: str
    name: str
    age: int


@app.put("/req/v1")
async def req(request: Request, des: str):
    req_method = request.method  # 请求的方式
    req_url = request.base_url  # 请求的路径
    req_port = request.url.port  # 请求的端口
    res_json = request.json()  # 请求json数据
    res_arg1 = request.url.query  # 请求查询参数1
    res_arg2 = request.query_params  # 请求查询参数2

    logger.info(
        f"请求的方式:{req_method},请求的路径:{req_url},#请求的端口:{req_port},请求json数据:{res_json}"
        f"请求查询参数1:{res_arg1},请求查询参数2:{res_arg2},des:{des}")
    return {"req_url": req_url, "res_arg1": res_arg1, "res_arg2": res_arg2}


@app.put("/req/v2")
async def req(item_query: Item = Depends()):
    logger.info(f"name:{item_query.name},age:{item_query.age},des:{item_query.des}")
    return {"name": item_query.name, "age": item_query.age, "des": item_query.des}


@app.post("/bar")
async def read_item(
        foo: int = Body(1, title='描述', embed=True),
        age: int = Body(..., le=120, title="年龄", embed=True),
        name: str = Body(..., regex="^哈哈\d+$", embed=True)
):
    logger.info(f"接收的参数:foo:{foo},age:{age},#name:{name}")
    return {"foo": foo, "age": age, "name": name}


if __name__ == "__main__":
    # 启停⽅式：
    # 1.⽅式1指令式：
    # 服务器启动指令 uvicorn main:app --reload
    # fastDemo1:app 表示main.py⽂件中的app实例
    # 服务器停⽌指令 ctrl+c
    # 2.⽅式2界⾯式：
    # ⿏标右键启动----》run main.py
    # 界⾯右上⻆的停⽌按钮
    # 启动服务,host指定主机地址,port指定端⼝号,reload=True表示当代码发⽣变化时,⾃动重启服务
    # main:app---- 表示main.py⽂件中的app实例
    logger.info("服务启动开始")
    uvicorn.run("app:app", host="127.0.0.1", port=8080, reload=True)
    logger.info("服务启动结束")
